import React, { useEffect, useMemo, useRef, useState } from "react";
import { formats, RichTextData } from "./Data";
import ReactQuill from "react-quill";
import { LibAppView } from "@/lib";
import lodash from 'lodash';
import { shouldSplitToUpload, UploadSplit } from "./UploadSplit";
import { message } from "antd";
import FileManage from "../../Component/FileManage";

interface IRichTextProps {
  value?: string;
  onChange?: Function;
}

const RichText = LibAppView.withService<IRichTextProps>()((props) => {
  const [content, setContent] = useState(props.value || '');
  const [ showChoseFile, setShowChoseFile ] = useState(false);
  const quillEdit = useRef<ReactQuill>(null);
  const handleImageUpload = () => {
    // 将文件转换为FormData
    // const editor = quillEdit.current?.getEditor();
    // const input = document.createElement('input')
    // input.setAttribute('type', 'file')
    // input.setAttribute('accept', 'image/*;')
    // input.setAttribute('multiple', 'multiple')
    // input.click()
    // input.onchange = async (event: any) => {
    //     const file = event.target.files[0];
    //     if(!shouldSplitToUpload(file)) {
    //       const formData = new FormData();
    //       formData.append('file', file, file.name);
    //       props.withServiceApi.send<any>({
    //         endPoint: "setting.uploadFile",
    //         data: formData,
    //         "isBinary": true,
    //       }).then((resp) => {
    //           const imgId = lodash.get(resp, "data.id");
    //           const imgUrl = "/resource/media/" + imgId;
    //           if(quillEdit.current) {
    //             const editor = quillEdit.current.getEditor();
    //             var cursorPosition = editor.getSelection(true).index;
    //             editor.insertEmbed(cursorPosition, "image", imgUrl);
    //             editor.setSelection(cursorPosition + 1, 1);
    //           }
    //       });
    //     } else {
    //       editor?.disable();
    //       const upload = new UploadSplit({
    //         file,
    //         blockSize: 1024 * 1024 * 2,
    //         service: props.withServiceApi,
    //         onFailed: () => {
    //           message.error('文件上传失败');
    //           editor?.enable();
    //           // setUploadPercent("");
    //         },
    //         onSuccess: (resp: any) => {
    //           const sourceUrl = resp?.data?.url || resp?.data?.id;
    //           const imgId = lodash.get(resp, "data.id");
    //           const imgUrl = "/resource/media/" + imgId;
    //           editor?.enable();
    //           if(editor) {
    //             var cursorPosition = editor.getSelection(true).index;
    //             editor.insertEmbed(cursorPosition, "image", imgUrl);
    //             editor.setSelection(cursorPosition + 1, 1);
    //           }
    //           // setLoading(false);
    //           // setUploadPercent("");
    //           // typeof props.onChange === "function" && props.onChange(sourceUrl, [{
    //           //   response: resp,
    //           //   uid: resp?.data?.id,
    //           //   name: file.name,
    //           //   size: file.size,
    //           //   status: 'done'
    //           // }]);
    //         },
    //         onProgress: ({ percent }: any) => {
    //           console.log(percent);
    //           // setUploadPercent("/" + percent + "%");
    //         }
    //       });
    //       upload.start();
    //     }
    // }
    setShowChoseFile(true);
  };
 
  const moduleData = useMemo(() => {
    return {
      ...RichTextData,
      toolbar: {
        ...RichTextData.toolbar,
        handlers: {
          image: handleImageUpload,
          // clipboard: {
          //   matchVisual: false,
          //   matchMimeType: 'image/png',
          //   callback: handleImage
          // }
        }
      },
    };
  }, []);
  useEffect(() => {
    if(quillEdit.current) {
      quillEdit.current.getEditor().clipboard.addMatcher(Node.ELEMENT_NODE, (node, delta) => {
        console.log(node, delta);
        if (node.nodeName === 'IMG') {
          return {
            ops: [{ insert: { image: node.getAttribute('src') } }],
          } as any;
        }
        return delta;
      });
    }
  }, []);
  console.log(showChoseFile);
  return (<>
      <ReactQuill
        ref={quillEdit}
        theme="snow"
        modules={moduleData}
        formats={formats}
        className="ql-editor"
        {...props}
        value={content}
        onChange={(value) => {
          setContent(value);
          typeof props.onChange === "function" && props.onChange(value);
        }} />
        { showChoseFile && <FileManage
          filterType="image"
          onConfirm={(fileList) => {
            const fileId = fileList[0];
            const imgUrl = "/resource/media/" + fileId;
            if(quillEdit.current) {
              const editor = quillEdit.current.getEditor();
              var cursorPosition = editor.getSelection(true).index;
              editor.insertEmbed(cursorPosition, "image", imgUrl);
              editor.setSelection(cursorPosition + 1, 1);
            }     
            setShowChoseFile(false);
          }}
          onCancel={() => {
            setShowChoseFile(false);
          }}
        /> }
      </>);
});

export default RichText;